window.lucode = {
    backstage: "/lucode-for-all-web/backstage",
    cms: "/lucode-for-all-web/cms",
    common: "/lucode-for-all-web/common",
    serverURL: "http://localhost:10000",
    QiQiImURL: "http://localhost:8080/qiqiim-server",
    // serverURL: "http://www.luyunfeng.cn:8080",
    // 统一文案配置
    WITHOUT_LOGIN: "请登陆后操作",
    NETWORK_ERROR: "网络请求异常,请检查你的网络<br/>(如果网络正常，就是我们服务器挂了!!!<br/>程序猿要被祭天了！)",

    SUCCESS: '9999',

    getHeader: function () {
        var userInfo = lucode.getCookie("lucode");
        var authToken = null;
        if (userInfo != null) {
            authToken = JSON.parse(userInfo).authToken;
        }
        var header = {
            "authToken": authToken
        };
        return header;
    },


    //打开登陆或者注册窗口
    openLoginWindow: function (type) {
        // 弹出窗大小
        var area = ['60%', '60%'];

        layer.open({
            type: 2,
            area: area,
            shadeClose: true,
            shade: [0.8, '#1C1C1C'],
            title: "",
            isOutAnim: false,
            content: lucode.common + '/' + type,
            cancel: function () {
                //关闭所有弹出窗
                layer.closeAll();
            }
        });
    },

    //打开新的窗口
    openWindow: function (url, area) {
        if (area == null) {
            area = ['80%', '80%'];
        }
        layer.open({
            type: 2,
            area: area,
            shadeClose: false,
            shade: [0.8, '#1C1C1C'],
            title: "",
            closeBtn: 1,// 按钮
            isOutAnim: false,
            content: url,
            cancel: function () {
                //关闭所有弹出窗
                layer.closeAll();
            }
        });
    },
    openWindowCheckLogin: function (url, area) {
        lucode.checkLogin(function () {
            lucode.openWindow(url, area)

        });
    },


    // 登陆
    login: function (oldUrl) {
        var url = this.serverURL + '/user/login';
        //layer.msg(vm.loginName,{time: 5000, icon:6});
        $.post(url, {
            loginName: vm.loginName,
            password: vm.password
        }, function (data, status) {
            console.log(data);
            if (data.resCode === lucode.SUCCESS) {
                //layer.msg(data.data.authToken);
                // 保存 Cookie，需要先将 json 对象转换成字符串
                var str = JSON.stringify(data.data);
                lucode.setCookie(str);
                var parentUrl = window.parent.location.href;
                if (parentUrl.indexOf('cms') >= 0) {
                    layer.msg("登录成功！", {time: 1000, icon: 1}, function () {
                        console.log(oldUrl);
                        //window.location.reload();
                        //layer.closeAll();
                        window.top.location.reload(lucode.cms);
                    });
                } else if (parentUrl.indexOf('back') >= 0) {
                    layer.msg("登录成功！欢迎登陆后台管理系统", {time: 1000, icon: 1}, function () {
                        window.parent.location.href = lucode.backstage;
                    });
                } else {
                    // 默认进入 后台登陆
                    layer.msg("登录成功！", {time: 1000, icon: 1}, function () {
                        window.location.href = lucode.backstage;
                    });
                }
            } else {
                layer.msg(data.resMsg, {time: 5000, icon: 5});
            }
        });
    },
    // 注册 第一步
    registerStep1: function () {
        var url = this.serverURL + '/user/registerStep1';
        //layer.msg(vm.loginName,{time: 5000, icon:6});
        $.post(url, {
            loginName: vm.loginName,
            password: vm.password,
            email: vm.email,
        }, function (data, status) {
            if (data.resCode === lucode.SUCCESS) {
                // 邮箱地址
                var mailUrl = data.data;
                layer.confirm('是否打开 ' + mailUrl + ' 页面？', {
                    btn: ['ok', 'no'] //按钮
                }, function () {

                    // 打开新的窗口
                    window.open(mailUrl);

                    layer.prompt({title: '邮件已发送，输入验证码，并确认', formType: 2}, function (verifCode, index) {
                        layer.close(index);
                        // 进入发送 注册第二步
                        lucode.registerStep2(verifCode);
                    });

                }, function () {
                    layer.prompt({title: '邮件已发送，输入验证码，并确认', formType: 2}, function (verifCode, index) {
                        layer.close(index);
                        // 进入发送 注册第二步
                        lucode.registerStep2(verifCode);
                    });
                });


            } else {
                layer.msg(data.resMsg, {time: 5000, icon: 5});
            }
        });
    },

    registerStep2: function (verifCode) {
        var url = this.serverURL + '/user/registerStep2';
        //layer.msg(vm.loginName,{time: 5000, icon:6});
        $.post(url, {
            loginName: vm.loginName,
            password: vm.password,
            email: vm.email,
            verifCode: verifCode
        }, function (data, status) {
            if (data.resCode === lucode.SUCCESS) {
                layer.msg("注册成功，正在自动登陆", {time: 2000, icon: 1}, function () {
                    // 调用登陆
                    lucode.login();
                })
            } else {
                layer.msg(data.resMsg, {time: 5000, icon: 5});
            }
        });
    },

    // 退出登陆
    layout: function () {
        lucode.confirm("是否退出登陆", null, function () {
            var c = lucode.getCookie("lucode");
            var parentUrl = window.parent.location.href;
            if (c != null) {
                $.get(lucode.serverURL + "/user/layout?authToken=" + JSON.parse(c).authToken,
                    function (data, status) {
                        if (data.resCode === lucode.SUCCESS) {
                            lucode.delCookie();
                            if (parentUrl.indexOf('cms') >= 0) {

                                window.parent.location.href = lucode.cms+"/index.html";
                            } else {
                                window.location.href = lucode.common + "/login.html";
                            }
                        }
                    });
            }
        });

    },

    // 确认 堵塞询问
    confirm: function (message, btn, fun) {
        if (btn == null) {
            btn = ['确认', '取消'];
        }
        layer.confirm(message, {
            btn: btn //按钮
        }, function () {
            fun();
        }, function () {
            return true;
        });
    },

    // 根据cookie 保存登录信息
    getCookie: function (cname) {
        var arr, reg = new RegExp("(^| )" + cname + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg)) {
            //console.log(arr);
            return (arr[2]);
        } else {
            return null;
        }
    },

    // 设置 cookie
    setCookie: function (cvalue) {
        var d = new Date();
        // 失效时间 10个小时
        d.setTime(d.getTime() + (60 * 60 * 1000 * 10));
        var expires = "expires=" + d.toUTCString();
        // 作用时间
        var path = " path=/";
        //console.info("lucode" + "=" + cvalue + "; " + expires);
        document.cookie = "lucode" + "=" + cvalue + "; " + expires + "; " + path;
        //console.info(document.cookie);
    },
    // 删除 cookie
    delCookie: function () {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = lucode.getCookie("lucode");
        console.info(cval);
        if (cval != null)
            document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    },

    //发送请求 到后端验证登录态是否存在
    checkLoginByAuthToken: function (userInfo, callback) {
        $.get(lucode.serverURL + "/user/getUserInfo?authToken=" + userInfo.authToken,
            function (data, status) {
                if (data.resCode === lucode.SUCCESS) {
                    // 更新Cookie，需要先将 json 对象转换成字符串
                    lucode.setCookie(JSON.stringify(userInfo));
                    //console.info("登陆检测完成，已更新保存事件");
                    callback();
                } else {
                    //console.info("服务端失效");
                    layer.alert(lucode.WITHOUT_LOGIN, {
                        skin: 'layui-layer-molv' //样式类名
                        , closeBtn: 0
                        , anim: 4
                    }, function () {
                        //window.location.href = "login.html";
                        lucode.openLoginWindow("login.html");
                    });
                }
            });
    },

    //本地登陆,先检查 cookie是否存在，然后检查服务端是否失效
    checkLogin: function (callback) {
        var c = lucode.getCookie("lucode");
        if (c != null) {
            lucode.checkLoginByAuthToken(JSON.parse(c), function () {
                callback();
            });
        } else {
            //console.info("客户端失效");
            layer.alert(lucode.WITHOUT_LOGIN, {
                skin: 'layui-layer-molv' //样式类名
                , closeBtn: 0
                , anim: 4
            }, function () {
                lucode.openLoginWindow("login.html");
            });
        }
    },

    //  异步得到用户信息的信息
    getLoginInfo: function (callback) {
        var serverUseInfo;
        var userCookie = lucode.getCookie("lucode");
        if (userCookie != null) {
            var localUserInfo = JSON.parse(userCookie);
            $.get(lucode.serverURL + "/user/getUserInfo?authToken=" + localUserInfo.authToken,
                function (data, status) {
                    if (data.resCode === lucode.SUCCESS) {
                        serverUseInfo = data.data;
                        callback(serverUseInfo);
                        //return data.data;
                    } else {
                        callback(serverUseInfo);
                    }
                });
        } else {
            callback(serverUseInfo);

        }

    },

    // 异步获取用户信息
    getUserInfo: function () {
        var userCookie = lucode.getCookie("lucode");
        if (userCookie != null) {
            return JSON.parse(userCookie).userInfo;
        } else {
            layer.alert(lucode.WITHOUT_LOGIN, {
                skin: 'layui-layer-molv' //样式类名
                , closeBtn: 0
                , anim: 4
            }, function () {
                lucode.openLoginWindow("login.html");
            });
            return false;
        }

    },

    // 同步 获取用户信息
    getUserInfoSyn:function (callback) {
        var userCookie = lucode.getCookie("lucode");
        if (userCookie != null) {
            callback(JSON.parse(userCookie).userInfo);
        } else {
            console.log("未登录，跳转至登陆页面");
            layer.alert(lucode.WITHOUT_LOGIN, {
                skin: 'layui-layer-molv' //样式类名
                , closeBtn: 0
                , anim: 4
            }, function () {
                lucode.openLoginWindow("login.html");
            });
            return false;
        }

    },

    // 打开窗口事件 检查 是否登录 只适合 带有 win10风格的
    openUrl: function (url, title, areaAndOffset) {
        lucode.checkLogin(function () {
            Win10.openUrl(url, title, areaAndOffset);
        });
    },


    // 请求示例
    // lucode.lucodeGet('http://127.0.0.1:10000/comm/get','restful',['3333','======'])
    // lucode.lucodeGet('http://127.0.0.1:10000/comm/get2', null, {'p1': '222', 'p2': '333'})
    // lucode.lucodePost('http://127.0.0.1:10000/comm/post', {'p1': '222', 'p2': '333'})
    // lucode.lucodePost('http://127.0.0.1:10000/comm/post2', {'name': 'lucode', 'age': 22})
    /**
     * 封装 post 请求
     * @param url
     * @param param
     * @param callback
     */
    lucodePost: function (url, param, callback) {
        $.ajax({
            type: "POST",
            url: url,
            data: param,
            dataType: "json",
            async: false,
            beforeSend: function (request) {
                // 循环遍历当前系统 的请求头
                var headers = lucode.getHeader();
                for (var header in headers) {//遍历json对象的每个key/value对,p为key
                    request.setRequestHeader(header, headers[header]);
                }
            },
            success: function (data) {
                if (data.resCode === lucode.SUCCESS) {
                    //layer.msg(data.resMsg, {time: 5000, icon: 1});
                    if (callback != null) {
                        callback(data);
                    } else {
                        return data;
                    }
                } else {
                    layer.msg(data.resMsg, {time: 5000, icon: 5});
                    return false;
                }
            },
            error: function () {
                layer.msg(lucode.NETWORK_ERROR, {time: 10000, icon: 5});
                return false;
            }
        });

    },

    /**
     * 封装Get 请求
     * @param url
     * @param type
     * @param param  restful
     */
    lucodeGet: function (url, type, param, callback) {
        // restful 风格就是 拼接 url。注意这个时候参数位置很重要
        if (type == "restful") {
            // 遍历数组 Param
            for (j = 0; j < param.length; j++) {
                url += "/" + param[j];
            }

            param = null;
        }
        $.ajax({
            type: "GET",
            url: url,
            data: param,
            dataType: "json",
            async: false,
            beforeSend: function (request) {
                // 循环遍历当前系统 的请求头
                var headers = lucode.getHeader();
                for (var header in headers) {//遍历json对象的每个key/value对,p为key
                    request.setRequestHeader(header, headers[header]);
                }
            },
            success: function (data) {
                if (data.resCode === lucode.SUCCESS) {
                    //layer.msg(data.resMsg, {time: 5000, icon: 1});
                    if (callback != null) {
                        callback(data);
                    } else {
                        return data;
                    }

                } else {
                    layer.msg(data.resMsg, {time: 5000, icon: 5});
                }
            },
            error: function () {
                layer.msg(lucode.NETWORK_ERROR, {time: 10000, icon: 5});
            }
        });
    },

    //正则匹配
    getStringByRegular: function (str) {
        var res = str.match(/[2][0-9]{31}/);
        if (res != null) {
            return res[0];
        } else {
            // 返回一个默认长度的
            return 1;
        }

    },

    // 获取 url 参数 中文 无效
    parseUrl:function (url) {
        var pattern = /(\w+)=(\w+)/ig;
        var parames = {};
        url.replace(pattern, function(a, b, c){
            parames[b] = c;
        });
        return parames;
    },

    formatDate: function (val) {
        Date.prototype.Format = function (fmt) {
            var o = {
                "M+": this.getMonth() + 1, //月份
                "d+": this.getDate(), //日
                "h+": this.getHours(), //小时
                "m+": this.getMinutes(), //分
                "s+": this.getSeconds() //秒
            };
            if (/(y+)/.test(fmt)) { //根据y的长度来截取年
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
            return fmt;
        };
        return new Date(val).Format("yyyy-MM-dd hh:mm:ss");

    }


};

